import { defineComponent, reactive, ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElCard,
  ElInput,
  ElButton,
  ElSpace,
  ElLink,
  ElMessageBox,
  ElMessage,
  ElIcon
} from 'element-plus'
import { EditPen } from '@element-plus/icons-vue'
import type { TableType, DelistingTableType } from './typings'
import type { TableColumnProps } from '~/components/ProSaasTable/typings'
import ProSaasTable from '~/components/ProSaasTable'
import ExportExcel from '~/components/ExportExcel'
import DelistingTableEdit from './DelistingTableEdit'
import useVuexGetters from '~/hooks/useVuexGetters'
import AliIcon from '~/components/AliIocn'

export default defineComponent({
  props: ['batchNum', 'discriminateArr'],
  setup(props, { expose }) {
    const userState = useVuexGetters('user', ['permission']) // 按钮权限
    const store = useStore()
    const proSaasTableRef = ref()
    const state = reactive<DelistingTableType>({
      exportVisible: false,
      delistingTableEditVisible: false,
      matchName: '',
      tableList: [],
      record: {},
      buildAreas: ''
    })
    const columns: TableColumnProps<TableType>[] = [
      {
        label: '站点名称',
        prop: 'matchName',
        minWidth: 200,
        sortable: true,
        align: 'center'
      },
      {
        label: '规划站号',
        prop: 'matchNum',
        minWidth: 160,
        sortable: true,
        align: 'center',
        render: ({ row }) => (
          <>
            {row.buildStatus === 1 ? <div style="color: red;">{row.matchNum}</div> : row.matchNum}
          </>
        )
      },
      {
        label: '需求类型',
        prop: 'requirementType',
        minWidth: 160,
        sortable: true,
        align: 'center',
        render: ({ row }) => (
          <>{row.requirementType === 2 ? <div style="color: blue;">特批</div> : '常规'}</>
        )
      },
      {
        label: '摘牌优先级',
        prop: 'delistingIndx',
        minWidth: 160,
        sortable: true,
        align: 'center',
        render: ({ row }) => (
          <>
            {row.delistingIndx === 1 && <div style="color: #D9001B;">1</div>}
            {row.delistingIndx === 2 && <div style="color: #F59A23;">2</div>}
            {row.delistingIndx === 3 && <div style="color: #333;">3</div>}
          </>
        )
      },
      {
        label: '预计折扣率(%)',
        prop: 'estDiscount',
        minWidth: 160,
        sortable: true,
        align: 'center'
      },
      {
        label: '实际折扣率(%)',
        prop: 'reaDiscount',
        minWidth: 160,
        sortable: true,
        align: 'center'
      },
      {
        label: '摘牌结果',
        prop: 'delistingRes',
        minWidth: 160,
        sortable: true,
        align: 'center',
        render: ({ row }) => (
          <>
            {row.delistingRes === 1 && <div style="color: #D9001B;">未投标</div>}
            {row.delistingRes === 2 && <div style="color: red;">中标</div>}
            {row.delistingRes === 3 && <div style="color: #4073ff;">流标</div>}
          </>
        )
      },
      {
        label: '我司排名',
        prop: 'ranking',
        minWidth: 160,
        sortable: true,
        align: 'center'
      },
      {
        label: '承建商',
        prop: 'contractor',
        minWidth: 160,
        sortable: true,
        align: 'center'
      },
      {
        label: '流标原因',
        prop: 'abortiveReson',
        minWidth: 160,
        sortable: true,
        align: 'center'
      },
      {
        label: '要求交付时间',
        prop: 'deliveryTime',
        minWidth: 160,
        sortable: true,
        align: 'center'
      },
      {
        label: '入库人',
        prop: 'delistingUser',
        minWidth: 160,
        sortable: true,
        align: 'center'
      },
      {
        label: '操作',
        prop: 'options',
        align: 'center',
        width: 160,
        render: ({ row }) => (
          <ElSpace>
            {userState.permission.value.has('basebuild_batch_edit') && !row.delistingRes ? (
              <ElLink type="primary" onClick={() => handleEdit(row)}>
                <ElIcon>
                  <EditPen />
                </ElIcon>
                &nbsp; 编辑
              </ElLink>
            ) : (
              <div style="color: #999">编辑</div>
            )}
            {userState.permission.value.has('basebuild_batch_remove') && !row.delistingRes ? (
              <ElLink type="danger" onClick={() => handleRemove(row)}>
                <AliIcon type="icon-yichu1" />
                &nbsp;移除&nbsp;&nbsp;
              </ElLink>
            ) : (
              <div style="color: #999">移除</div>
            )}
          </ElSpace>
        )
      }
    ]

    //  导出
    const handleChangeExportModal = () => {
      state.exportVisible = !state.exportVisible
    }
    // 按回车搜索列表
    const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
      if ((evt as KeyboardEvent).key === 'Enter') index()
    }
    // 清空搜索
    const clearSearchTable = async () => {
      setTimeout(() => {
        index()
      }, 100)
    }

    const index = async () => {
      const { code, data } = await store.dispatch('base/GetBasebuildbatchDistingList', {
        batchNum: props.batchNum,
        matchName: state.matchName,
        buildAreas: state.buildAreas,
        size: 1000
      })
      if (code === 200) {
        state.tableList = data.records
      }
    }
    //  工区搜索
    const buildAreasAjax = (buildAreas: string) => {
      state.buildAreas = buildAreas
      index()
    }

    //  移除
    const handleRemove = (row: TableType) => {
      ElMessageBox.confirm('是否移除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { code, msg } = await store.dispatch('base/GetBasebuildbatchRemoveDelisting', {
            assetBaseBuildId: row.id
          })
          if (code === 200) {
            index()
            ElMessage({
              type: 'success',
              message: msg
            })
          }
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消操作'
          })
        })
    }
    //  编辑
    const handleEdit = (row: TableType) => {
      state.delistingTableEditVisible = !state.delistingTableEditVisible
      if (state.delistingTableEditVisible) {
        state.record = row
      }
    }

    onMounted(() => {
      state.buildAreas = props.discriminateArr
      index()
    })
    expose({ buildAreasAjax })
    return () => (
      <ElCard>
        <ProSaasTable<TableType>
          ref={proSaasTableRef}
          tableId="DelistingTable"
          columns={columns}
          needPagination={false}
          data={state.tableList}
          height={540}
          headerTitle={
            <>
              <ElInput
                v-model={state.matchName}
                {...{ maxlength: 30 }}
                placeholder="站点名称 回车搜索"
                clearable
                onKeydown={handleKeyDownEnterSubmitForm}
                onClear={clearSearchTable}
                style="width: 240px;"
              />
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              {userState.permission.value.has('basebuild_batch_export') && (
                <ElButton type="primary" onClick={() => handleChangeExportModal()}>
                  &nbsp; 导出
                </ElButton>
              )}
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              <span>
                共计 <span style="color: #4073ff;">{state.tableList?.length}</span> 条数据
              </span>
            </>
          }
        ></ProSaasTable>
        {/* 导出 */}
        {state.exportVisible && (
          <ExportExcel
            visible={state.exportVisible}
            dispatchType="base/BasebuildbatchExport"
            columns={proSaasTableRef.value?.filterColumns}
            payload={{
              params: {
                matchName: state.matchName,
                batchNum: props.batchNum,
                buildAreas: props.discriminateArr,
                exportName: props.batchNum
              }
            }}
            exportNumber={proSaasTableRef.value?.pagination.total}
            onCancel={handleChangeExportModal}
          />
        )}
        {/* 摘牌库编辑 */}
        {state.delistingTableEditVisible && (
          <DelistingTableEdit
            record={state.record}
            cancel={handleEdit}
            onSubmitForm={() => index()}
          />
        )}
      </ElCard>
    )
  }
})
